﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using Castle.Core.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.IO;
using System.Text.RegularExpressions;
using MvcContrib.Sorting;
using MvcContrib.UI.Grid;
using MvcContrib.Pagination;
using System.Data.Entity.Validation;

using System.Xml;

using CooWork.Models;
using CooWork.Services;
using CooWork.Core;
using Coowork.Data.Mapping;

namespace CooWork.Controllers
{
    public class DataController : BaseController
    {
        private readonly ITaskAuth ita;
        //
        // GET: /Data/
        private CooWorkEntities context = new CooWorkEntities();



        public DataController(ITaskAuth iTaskAuth)
        {
            this.ita = iTaskAuth;
        }



        public PartialViewResult ddlroles(string name, string value)
        {
            var ddlist = new _DropDownModel();
            ddlist.SelectedString = value;
            ddlist.Name = string.IsNullOrWhiteSpace(name) ? ddlist.Name : name;
            ddlist.ddlroles();
            return PartialView(ddlist);
        }


        public ActionResult Index()
        {
            return View();
        }


        public PartialViewResult ddl(string name, int? parentId)
        {
            var ddlist = new _DropDownModel();
            ddlist.SelectedID = parentId ?? -1;
            ddlist.Name = string.IsNullOrWhiteSpace(name) ? ddlist.Name : name;
            ddlist.ddltask();
            return PartialView(ddlist);
        }



        public PartialViewResult ddlpriority(string name, int? priority)
        {
            var ddlist = new _DropDownModel();
            ddlist.SelectedID = priority ?? -1;
            ddlist.Name = string.IsNullOrWhiteSpace(name) ? ddlist.Name : name;
            ddlist.ddlpriority();
            return PartialView(ddlist);
        }




        public PartialViewResult ddlseverity(string name, int? severity)
        {
            var ddlist = new _DropDownModel();
            ddlist.SelectedID = severity ?? -1;
            ddlist.Name = string.IsNullOrWhiteSpace(name) ? ddlist.Name : name;
            ddlist.ddlseverity();
            return PartialView(ddlist);
        }









        public JsonResult priority() 
        {
            List<KeyValuePair<int, string>> r = new List<KeyValuePair<int, string>>();
               
            foreach (int i in CacheSet.priorityCache.Keys)
            {
                r.Add(new KeyValuePair<int, string>(i, CacheSet.priorityCache[i]));  
            }

            var result = new JsonNetResult
            {
                Data = r,
                JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                Settings = { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }
            };
            return result;
        }


        public JsonResult severity()
        {
            List<KeyValuePair<int, string>> r = new List<KeyValuePair<int, string>>();

            foreach (int i in CacheSet.severityCache.Keys)
            {
                r.Add(new KeyValuePair<int, string>(i, CacheSet.severityCache[i]));
            }

            var result = new JsonNetResult
            {
                Data = r,
                JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                Settings = { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }
            };
            return result;
        }
        

        public JsonResult status()
        {
            List<KeyValuePair<int, string>> r = new List<KeyValuePair<int, string>>();

            foreach (int i in CacheSet.StatusCache.Keys)
            {
                r.Add(new KeyValuePair<int, string>(i, CacheSet.StatusCache[i]));
            }

            var result = new JsonNetResult
            {
                Data = r,
                JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                Settings = { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }
            };
            return result;
        }




        public JsonResult feedbacklist(int? taskId)
        {
            var cid=UserService.UcId();
            if (!taskId.HasValue) return new JsonResult();
            var ctask = context.CooTasks.Single(x => x.ID == taskId);

            List<KeyValuePair<System.Guid, string>> r = new List<KeyValuePair<System.Guid, string>>();
           

            if (ctask.Creator.HasValue)
            r.Add(new KeyValuePair<System.Guid, string>(ctask.Creator.Value, CacheSet.U2N(cid, ctask.Creator.Value)));
            if (ctask.Owner.HasValue)
            r.Add(new KeyValuePair<System.Guid, string>(ctask.Owner.Value, CacheSet.U2N(cid, ctask.Owner.Value)));

            string[] args = ctask.EditableList.Split(',');
            foreach (string s in args)
            {
                Guid gid = new Guid(s);
                r.Add(new KeyValuePair<System.Guid, string>(gid, CacheSet.U2N(cid, gid)));
            }

            var ret = r.Distinct();

            var result = new JsonNetResult
            {
                Data = ret,
                JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                Settings = { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }
            };
            return result;


        }


        public ContentResult totalOrg()
        {                   

            List<CUserList> lcl = UserService.GetCUserList(UserService.UcId(),true);
            Dictionary<string, TreeNode> lookup = new Dictionary<string, TreeNode>();
            lcl.ForEach(x => lookup.Add(x.Userid, new TreeNode(x.Userid, x.Username, x.Id, x.Parentid, true)));

            int currentPid = 0;
            foreach (CUserList cul in lcl)
            {
                if (cul.Id != currentPid)
                {
                    lookup.Add("department_" + cul.Id.ToString(), new TreeNode("department_" + cul.Id.ToString(), cul.Departmentname, cul.Id, cul.Parentid, false));
                    currentPid = cul.Id;
                }
            }

            foreach (var item in lookup.Values)
            {
                TreeNode proposedParent;
                var pid = item.ID.Contains("department") ? item.ParentId : item.Did;
                if (lookup.TryGetValue("department_" + pid, out proposedParent))
                {
                    //item.Parent = proposedParent;              
                    proposedParent.Add(item);
                }
            }

            var r = lookup.Values.Where(x => x.Parent == null).Where(x => x.ID.Contains("department")).SingleOrDefault();
            string ret = UserService.GetTreeJson(r);       
            return new ContentResult { Content = ret, ContentType = "application/json" };
        }



        public ContentResult department()
        {
            string ret = _comDepartment(true);
            return new ContentResult { Content = ret, ContentType = "application/json" };
        }


        public PartialViewResult _department(string name, int? id)
        {

            var ddlist = new _DropDownModel();
            ddlist.SelectedID =id ?? -1;
            ddlist.Name = string.IsNullOrWhiteSpace(name) ? ddlist.Name : name;
            ddlist.ddldepartment();
            return PartialView(ddlist);
        }

 
      

        private string _comDepartment(bool reset)
        {
            //don't cache list
            List<CUserList> lcl = UserService.GetDepartmentList(UserService.UcId(), reset);          

            Dictionary<string, TreeNode> lookup = new Dictionary<string, TreeNode>();

            lcl.ForEach(x => lookup.Add(x.Userid, new TreeNode(x.Userid, x.Departmentname, x.Id, x.Parentid, false)));
            

            foreach (var item in lookup.Values)
            {
                TreeNode proposedParent;
                var pid = item.ID.Contains("department") ? item.ParentId : item.Did;

                if (pid!=null&&lookup.TryGetValue("department_" + pid, out proposedParent))
                {
                    //item.Parent = proposedParent;              
                    proposedParent.Add(item);
                }
            }

            var r = lookup.Values.Where(x => x.Parent == null).Where(x => x.ID.Contains("department")).SingleOrDefault();

            string ret = UserService.GetTreeJson(r);

            return ret;

        }



        private string _comStr()
        {
            List<CUserList> lcl = UserService.GetCUserList(UserService.UcId(), false);

            Dictionary<string, TreeNode> lookup = new Dictionary<string, TreeNode>();

            lcl.ForEach(x => lookup.Add(x.Userid, new TreeNode(x.Userid, x.Username, x.Id, x.Parentid, true)));

            int currentPid = 0;

            foreach (CUserList cul in lcl)
            {
                if (cul.Id != currentPid)
                {
                    lookup.Add("department_" + cul.Id.ToString(), new TreeNode("department_" + cul.Id.ToString(), cul.Departmentname, cul.Id, cul.Parentid, false));
                    currentPid = cul.Id;
                }
            }

            foreach (var item in lookup.Values)
            {
                TreeNode proposedParent;
                var pid = item.ID.Contains("department") ? item.ParentId : item.Did;

                if (lookup.TryGetValue("department_" + pid, out proposedParent))
                {
                    //item.Parent = proposedParent;              
                    proposedParent.Add(item);
                }
            }

            var r = lookup.Values.Where(x => x.Parent == null).Where(x => x.ID.Contains("department")).SingleOrDefault();

            string ret = UserService.GetTreeJson(r);

            return ret;

        }


        public ContentResult owner(int? taskId)
        {
        
       //     List<KeyValuePair<string, string>> r = new List<KeyValuePair<string, string>>();

            List<CUserList> lcl = UserService.GetCUserList(UserService.UcId(),false);

            Dictionary<string, TreeNode> lookup = new Dictionary<string, TreeNode>();

            lcl.ForEach(x => lookup.Add(x.Userid, new TreeNode(x.Userid,x.Username,x.Id,x.Parentid,true)));



            int currentPid = 0;

            foreach (CUserList cul in lcl)
            {
                if (cul.Id != currentPid)
                {
                    lookup.Add("department_" + cul.Id.ToString(),new TreeNode("department_" + cul.Id.ToString(), cul.Departmentname, cul.Id, cul.Parentid, false));
                    currentPid = cul.Id;
                }              
            }
     
            foreach (var item in lookup.Values)
            {
                TreeNode proposedParent;
                var pid = item.ID.Contains("department")?item.ParentId:item.Did;
            
                if (lookup.TryGetValue("department_" + pid, out proposedParent))
                {
                    //item.Parent = proposedParent;              
                    proposedParent.Add(item);
                }
      
            }

            var r = lookup.Values.Where(x => x.Parent == null).Where(x => x.ID.Contains("department")).SingleOrDefault();




      
            string ret = UserService.GetTreeJson(r);

            //
            /* authorize control
              
            if (taskId.HasValue)
            {
                TaskEditableRole ter = ita.UserRoleForSpecTask(taskId.Value, UserService.UcId());

                switch (ter)
                {
                    case TaskEditableRole.AdminGroup:
                        break;
                    default:
                        break;
                }
            }
            */








           return  new ContentResult { Content = ret, ContentType = "application/json" };
        }

       
    }
}
